//
//  ZZCAddressController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/23.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCAddressController.h"
#import "ZZCAddressCell.h"
#import "ZZCAddAddressController.h"
#import "ZZCEditAddressController.h"
#import "ZZCDeleteView.h"
#import "ZZCAddress.h"

static NSString *addressCell = @"addressCell";
@interface ZZCAddressController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) UITableView *addressTableView;
@property (strong, nonatomic) ZZCDeleteView *deleteView;
@property (strong, nonatomic) NSArray *addressData;
@property (assign, nonatomic) BOOL isSelect;//选中的默认地址
@property (assign, nonatomic) NSInteger select;
@end

@implementation ZZCAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = ZZCBGColor;
    self.title = @"收货地址";
    [self.view addSubview:self.addressTableView];
    self.isSelect = NO;
    self.select = -1;
    [self bottomAddressBtn];
    [self requestAddAreaData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAddAreaData) name:@"addressUpdate" object:nil];
}

- (void)bottomAddressBtn {
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, ZZCScreenH-113, ZZCScreenW, 49)];
    btn.backgroundColor = [UIColor colorWithHex:0xEA6E25];
    [btn setTitle:@"添加新地址" forState:0];
    [btn addTarget:self action:@selector(addAddressClick) forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = FONT(19);
    [self.view addSubview:btn];
}

//添加新地址按钮监听
- (void)addAddressClick {
    ZZCLog(@"你点击了新添加地址按钮");
    ZZCAddAddressController *add = [ZZCAddAddressController new];
    [self.navigationController pushViewController:add animated:YES];
}

- (void)requestAddAreaData {
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *dict = @{@"token":token};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"token":token};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_ADDRESS parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            ZZCLog(@"-%@",responseObject);
            self.addressData = [ZZCAddress mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"list"]];
            [self.addressTableView reloadData];
            
        }
    }];
}



#pragma mark - 数据源方法

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.addressData.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZZCAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:addressCell];
    cell.selectionStyle = 0;
    cell.imgBtn.tag = indexPath.row;
    cell.editView.tag = indexPath.row;
    cell.deleteView.tag = indexPath.row;
    //编辑
    cell.editView.userInteractionEnabled = YES;
    UITapGestureRecognizer *editTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editClick:)];
    [cell.editView addGestureRecognizer:editTap];
    //删除
    cell.deleteView.userInteractionEnabled = YES;
    UITapGestureRecognizer *deleteTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(deleteClick:)];
    [cell.deleteView addGestureRecognizer:deleteTap];
    //默认选中框
    [cell.imgBtn addTarget:self action:@selector(imgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    if (!self.isSelect) {
        if (indexPath.row == 0) {
             [cell.imgBtn setImage:[UIImage imageNamed:@"圆_pressed"] forState:0];
        }else {
             [cell.imgBtn setImage:[UIImage imageNamed:@"圆_normal"] forState:0];
        }
       
    }else {
        if (indexPath.row == self.select) {
            [cell.imgBtn setImage:[UIImage imageNamed:@"圆_pressed"] forState:0];
        }else {
            [cell.imgBtn setImage:[UIImage imageNamed:@"圆_normal"] forState:0];
        }
    }
    cell.addressModel = self.addressData[indexPath.row];
    return cell;
    
}

- (void)imgBtnClick:(UIButton *)btn {
    self.isSelect = YES;
    self.select = btn.tag;
//    [self.addressTableView reloadData];
    ZZCAddress *Add = self.addressData[btn.tag];
    NSString *token = ZZCNSUserDefaults(@"token");
    NSDictionary *dict = @{@"id":Add.id,
                           @"token":token};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,
                            @"id":Add.id,
                            @"token":token};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_DEFAULTADDRESS parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            ZZCLog(@"-%@",responseObject);
            NSLog(@"成功");
            [self requestAddAreaData];
            self.isSelect = NO;
//            [self.addressTableView reloadData];
        }
    }];

}

//编辑
- (void)editClick:(UITapGestureRecognizer *)tap {
    ZZCLog(@"编辑--%ld",(long)tap.view.tag);
    ZZCEditAddressController *edit = [ZZCEditAddressController new];
    ZZCAddress *add = self.addressData[tap.view.tag];
    edit.id = add.id;
    edit.name = add.receiver;
    edit.phone = add.tel;
    edit.areaText = [NSString stringWithFormat:@"%@-%@-%@",add.province,add.city,add.area];
    edit.address = add.street;
    [self.navigationController pushViewController:edit animated:YES];
}
//删除
- (void)deleteClick:(UITapGestureRecognizer *)tap {
    ZZCLog(@"删除--%ld",(long)tap.view.tag);
    [self.view addSubview:self.deleteView];
    self.deleteView.deleteBtn.tag = tap.view.tag;
    [self.deleteView.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.deleteView.cancelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
}
- (void)deleteBtnClick:(UIButton *)sender {
    ZZCLog(@"删除-");
    [self requestDleAddAreaData:sender.tag];
    [self.deleteView removeFromSuperview];
}

- (void)requestDleAddAreaData:(NSInteger)index {
    NSString *token = ZZCNSUserDefaults(@"token");
    ZZCAddress *add = self.addressData[index];
    NSDictionary *dict = @{@"id":add.id,@"token":token};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:[sign lowercaseString]];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"id":add.id,@"token":token};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_DELADDRESS parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
        }else {
            ZZCLog(@"-%@",responseObject);
            [self requestAddAreaData];
            
        }
    }];
}

- (void)cancelBtnClick {
    ZZCLog(@"取消-");
    [self.deleteView removeFromSuperview];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 125;
}

#pragma mark - 懒加载
- (UITableView *)addressTableView {
    if (_addressTableView == nil) {
        _addressTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ZZCScreenW, ZZCScreenH-113)];
        [_addressTableView registerNib:[UINib nibWithNibName:@"ZZCAddressCell" bundle:nil] forCellReuseIdentifier:addressCell];
        _addressTableView.delegate = self;
        _addressTableView.dataSource = self;
        _addressTableView.separatorStyle = NO;
        _addressTableView.showsVerticalScrollIndicator = NO;
        _addressTableView.backgroundColor = ZZCBGColor;
 
    }
    return _addressTableView;
}


- (NSArray *)addressData {
    if (_addressData == nil) {
        _addressData = [NSArray array];
    }
    return _addressData;
}

- (ZZCDeleteView *)deleteView {
    if (_deleteView == nil) {
        _deleteView = [ZZCDeleteView deleteView];
        _deleteView.frame = CGRectMake(0, 0, ZZCScreenW, ZZCScreenH);
        _deleteView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    }
    return _deleteView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
